
import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import { notification, message } from 'antd';
import { history } from 'umi';
import { getAuthority } from '@/utils/authority';
import type { RequestConfig } from 'umi';
import 'moment/locale/zh-cn'; //全局汉化日期选择器
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/login';
const noAuthStatus: number = 401;

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @param 获取用户信息监听，登录的时候，传递过来
 * @returns 
 */

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: {
    nickName: string;
    token: string;
    logo: string | null;
    userid: string;
  };
  fetchUserInfo?: () => Promise<any>;
}> {

  const fetchUserInfo = async () => {
    try {
      const currentUser = getAuthority(); // await queryCurrentUser();
      return currentUser;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = getAuthority();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

/**
 * 异常处理程序
 
 * @see https://beta-pro.ant.design/docs/request-cn
 */
// 新增自动添加AccessToken的 请求前拦截器
const authHeaderInterceptor = (url: string, options: any) => {
  return {
    url,
    options: {
      ...options,
      interceptors: true,
      headers: { token: getAuthority()?.token || '', 'Content-Type': 'application/json', }
    },
  };
};

// 响应后拦截
const demoResponseInterceptors = (response: Response, options: any) => {
  if (response && response.status == noAuthStatus) {
    // history.push(loginPath);
    console.warn('淑珍：暂时先注释掉 window.location.href 的重定向，登录接完再放开');
    // window.location.href = `${window.location.origin}${isDev ? '' : `/portal`}/login`;
  }
  return response;
};

let key = 0;

// 请求拦截器
export const request: RequestConfig = {
  timeout: 60000,
  errorHandler: (error: any) => {

    const { response } = error;
    if (response?.status === 403) {
      history.push('/login');

      if (key == 0) {
        notification.error({
          message: '无权访问，请重新登录',
        });
        key = 1;
      }

    }
    if (response?.status === 401) {
      history.push('/login');

      if (key == 0) {
        notification.error({
          message: '登录过期，请重新登录',
        });
        key = 1;
      }

    }
    if (!response) {
      notification.error({
        description: '您的网络发生异常，无法连接服务器',
        message: '网络异常',
      });
    }
    throw error;
  },
  requestInterceptors: [authHeaderInterceptor],// 请求前拦截器
  responseInterceptors: [demoResponseInterceptors],// 响应后拦截
};
